﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using Wp.BLL;
using Wp.DAL;


public partial class Admin_Modules_Posts_PostEdit : System.Web.UI.Page
{
    public int? Id { get; set; }
    protected void Page_Load(object sender, EventArgs e)
    {
        Id = CommonHelper.QueryStringInt("Id", null);
        if (!IsPostBack)
        {
            LoadData();
        }
    }
    void LoadData()
    {
        LoadDDLAuthor();

        if (!Id.HasValue)
        {
            CategoryList1.LoadData();
            return;
        }
        CategoryList1.LoadData(Id.Value);
        CategoryList1.LoadData();
        TblPostsEntity item = TblPostsManager.CreateInstant().SelectOne(Id.Value, true);
        txtTitle.Text = item.Title;
        txtSummary.Text = item.Summary;
        radEditorContent.Content = item.Description;
        ddlAuthor.SelectedValue = item.Author;
        ddlpublish.SelectedValue = item.PostStatus;
        if (item.PublishDate != new DateTime(1900, 1, 1))
            txtPublishDate.Text = item.PublishDate.ToString("dd-MM-yyyy H:mm:ss");
        else txtPublishDate.Text = "";
        imgThumb.ImageUrl = item.ImageUrl;
        hdfimg.Value = item.ImageUrl;
        txtTag.Text = TblTermRelationshipsManager.CreateInstant().GetStringTagsList(Id.Value, "posttags");
        txtSEOTitle.Text = item.PostMetas["SEOTitle"] != null ? item.PostMetas["SEOTitle"].ToString() : "";
        txtSEODescription.Text = item.PostMetas["SEODescription"] != null ? item.PostMetas["SEODescription"].ToString() : "";
        txtSEOKeyWord.Text = item.PostMetas["SEOKeyWord"] != null ? item.PostMetas["SEOKeyWord"].ToString() : "";

    }
    void LoadDDLAuthor()
    {
        List<UserEntity> ls = GetAllUser();
        ddlAuthor.DataSource = ls;
        ddlAuthor.DataTextField = "FullName";
        ddlAuthor.DataValueField = "UserName";
        ddlAuthor.DataBind();
    }
    public List<UserEntity> GetAllUser()
    {
        MembershipUserCollection uc = Membership.GetAllUsers();
        List<UserEntity> ls = new List<UserEntity>();
        foreach (MembershipUser user in uc)
        {
            UserEntity i = new UserEntity();
            i.UserName = user.UserName;
            ProfileCommon f = Profile.GetProfile(user.UserName);
            if (f != null)
                i.FullName = f.FullName;
            else
                i.FullName = user.UserName;
            ls.Add(i);
        }
        return ls;
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        int _Id = TblPostsManager.CreateInstant().InsertUpdate(GetTblPostsEntity());
        if (_Id != -1)
        {
            CategoryList1.Update(_Id);
            string[] str = txtTag.Text.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            TblTermRelationshipsManager.CreateInstant().DeleteByObjectIdAndTaxonomy(_Id, "posttags");
            for (int i = 0; i < str.Length; i++)
            {
                TblTermTaxonomyManager.CreateInstant().InsertPostTag(_Id, str[i], "posttags");
            }
            List<TblPostMetaEntity> lsmeta = TblPostMetaManager.CreateInstant().SelectByPostId(_Id);
            if (lsmeta != null)
            {
                TblPostMetaEntity itemnumview = lsmeta.Where(n => n.MetaKey.Equals("NumView")).SingleOrDefault();
                if (itemnumview == null)
                {
                    TblPostMetaManager.CreateInstant().InsertUpdate(-1, _Id, "NumView", "1");
                }
                TblPostMetaEntity itemtitle = lsmeta.Where(n => n.MetaKey.Equals("SEOTitle")).SingleOrDefault();
                if (itemtitle != null)
                {
                    itemtitle.MetaValue = txtSEOTitle.Text;
                    TblPostMetaManager.CreateInstant().InsertUpdate(itemtitle);
                }
                else if (!txtSEOTitle.Text.Equals(""))
                {
                    TblPostMetaManager.CreateInstant().InsertUpdate(-1, _Id, "SEOTitle", txtSEOTitle.Text);
                }

                TblPostMetaEntity itemkeyword = lsmeta.Where(n => n.MetaKey.Equals("SEOKeyWord")).SingleOrDefault();
                if (itemkeyword != null)
                {
                    itemkeyword.MetaValue = txtSEOKeyWord.Text;
                    TblPostMetaManager.CreateInstant().InsertUpdate(itemtitle);
                }
                else if (!txtSEODescription.Text.Equals(""))
                {
                    TblPostMetaManager.CreateInstant().InsertUpdate(-1, _Id, "SEODescription", txtSEODescription.Text);
                }
                TblPostMetaEntity itemdescription = lsmeta.Where(n => n.MetaKey.Equals("SEODescription")).SingleOrDefault();
                if (itemdescription != null)
                {
                    itemdescription.MetaValue = txtSEODescription.Text;
                    TblPostMetaManager.CreateInstant().InsertUpdate(itemdescription);
                }
                else if (!txtSEOKeyWord.Text.Equals(""))
                {
                    TblPostMetaManager.CreateInstant().InsertUpdate(-1, _Id, "SEOKeyWord", txtSEOKeyWord.Text);
                }
            }
            Response.Redirect("PostEdit.aspx?Id=" + _Id);
        }


    }
    TblPostsEntity GetTblPostsEntity()
    {
        TblPostsEntity item = new TblPostsEntity();
        if (Id.HasValue)
        {
            item = TblPostsManager.CreateInstant().SelectOne(Id.Value);
        }
        else
        {
            item.TextId = TblPostsManager.CreateInstant().GetUniqueTextIdFromUnicodeText(txtTitle.Text.Trim());
            item.PostType = "post";
            item.Url = "";
            item.CreatedBy = HttpContext.Current.User.Identity.Name;
            item.CreatedDate = DateTime.Now;
            item.DisplayOrder = 1;
            item.ParentId = -1;
            item.CommentStatus = "allow";//prohibit
            item.PublishDate = DateTime.Now;
        }
        item.Title = txtTitle.Text;
        item.Summary = txtSummary.Text.Trim();
        item.Description = radEditorContent.Content;
        item.ImageUrl = hdfimg.Value;
        item.Author = ddlAuthor.SelectedValue;
        item.ModifiedBy = HttpContext.Current.User.Identity.Name;
        DateTime datetime = new DateTime(1900, 1, 1);
        if (chbChangeDateTime.Checked)
        {
            if (!txtPublishDate.Text.Equals(""))
            {
                DateTime.TryParse(txtPublishDate.Text, CultureInfo.CreateSpecificCulture("vi-VN"), DateTimeStyles.None, out datetime);
                item.CreatedDate = datetime;
            }
            else
            {
                item.CreatedDate = DateTime.Now;
            }
            item.PublishDate = datetime;
        }

        item.PostStatus = ddlpublish.SelectedValue;
        item.ModifiedDate = DateTime.Now;
        return item;
    }


    public string Taxonomy { get; set; }
}